package com.noble.glamour.module.local.login;

import android.text.TextUtils;

import com.noble.glamour.bean.start.UP;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.config.Constant;
import com.noble.glamour.module.logic.config.FinalKey;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.util.BaseUtil;
import com.noble.glamour.module.util.NotificationsUtils;
import com.noble.glamour.module.util.TimeUtil;
import com.noble.library.third.ThirdConstant;
import com.noble.library.third.auth.ThirdInfo;
import com.noble.library.log.PLogger;
import com.noble.library.log.PSP;
import com.noble.library.observe.ModuleBase;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.utils.EncryptUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 登录逻辑处理
 * Created by ZRP on 2016/9/19.
 */
public class LoginMgr implements ModuleBase {

    private final static String LOGINMGR_UID = "LOGINMGR_UID";          // 保存当前登录用户账号信息 uid, pw
    private final static String LOGINMGR_COOKIE = "LOGINMGR_COOKIE";    // 保存当前登录用户cookie
    private final static String LOGINMGR_AUTH = "LOGINMGR_AUTH";        // 保存当前登录用户cookie, 不带auth=

    @Override
    public void init() {
    }

    @Override
    public void release() {
    }

    /**
     * 获取手机登录验证码
     */
    public void reqSendCode(String mobile, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("mobile", mobile);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqSendCode, postParams, complete);
    }

    /**
     * 手机号验证码验证
     */
    public void reqVerifyCode(String mobile, String code, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("mobile", mobile);
        postParams.put("code", code);
        postParams.put("platform", "android");
        postParams.put("ver", Constant.SUB_VERSION);
        postParams.put("ms", Constant.MS_TYPE);
        postParams.put("app_key", EncryptUtil.sha1(ModuleMgr.getAppMgr().getSignature()));
        postParams.put("pkgname", ModuleMgr.getAppMgr().getPackageName());
        postParams.put("ie", ModuleMgr.getAppMgr().getIMEI());
        postParams.put("is", ModuleMgr.getAppMgr().getIMSI());
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqVerifyCode, postParams, complete);
    }

    /**
     * 微信三方登录
     */
    public void weChatLogin(String openId, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("openid_wechat", openId);
        postParams.put("platform", "android");
        postParams.put("ver", Constant.SUB_VERSION);
        postParams.put("ms", Constant.MS_TYPE);
        postParams.put("app_key", EncryptUtil.sha1(ModuleMgr.getAppMgr().getSignature()));
        postParams.put("pkgname", ModuleMgr.getAppMgr().getPackageName());
        postParams.put("ie", ModuleMgr.getAppMgr().getIMEI());
        postParams.put("is", ModuleMgr.getAppMgr().getIMSI());
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.weChatLogin, postParams, complete);
    }

    private static ThirdInfo thirdInfo;  // 三方登录保存数据

    /**
     * 获取第三方的用户信息
     */
    public static ThirdInfo getThirdInfo() {
        if (thirdInfo == null) {
            thirdInfo = new ThirdInfo();
        }
        return thirdInfo;
    }

    public void setThirdInfo(ThirdInfo thirdInfo) {
        this.thirdInfo = thirdInfo;
    }

    /**
     * 微信获取AccessToken
     */
    public void loadAccessToken(String code, RequestComplete complete) {
        HashMap<String, Object> getParams = new HashMap<>();
        getParams.put("appid", ThirdConstant.WEIXIN_APP_ID);
        getParams.put("secret", ThirdConstant.WEIXIN_APP_SECRET);
        getParams.put("code", code);
        getParams.put("grant_type", "authorization_code");
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.getWXAccessToken, getParams, complete);
    }

    /**
     * 微信获取用户资料
     */
    public void loadUserInfo(String openid, String accessToken, RequestComplete complete) {
        HashMap<String, Object> getParams = new HashMap<>();
        getParams.put("access_token", accessToken);
        getParams.put("openid", openid);
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.getWXUserInfo, getParams, complete);
    }

    /**
     * 保存登录信息
     */
    public void putAllLoginInfo(long uid, String md5Password, boolean isUserLogin) {
        setUid(uid + "");
//        putUserInfo(uid, password); //保存登录账户到list配置, 已经无用
        setLoginInfo(uid, isUserLogin);  //设置登录状态
    }

    /**
     * 判断Cookie是否存在
     */
    public boolean checkAuthIsExist() {
        return !TextUtils.isEmpty(getCookie());
    }

    /**
     * 清空本地Cookie
     */
    public void clearCookie() {
        setCookie("");
    }

    /**
     * 保存cookie
     */
    public void setCookie(String cookie) {
        PLogger.d("yao=" + cookie);
        PSP.getInstance().put(LOGINMGR_COOKIE, "auth=" + cookie);
        PSP.getInstance().put(LOGINMGR_AUTH, cookie);
    }

    /**
     * 获取cookie
     */
    public String getCookie() {
        return PSP.getInstance().getString(LOGINMGR_COOKIE, "");
    }

    /**
     * @return 获取无 auth= 的cookie
     */
    public String getAuth() {
        return PSP.getInstance().getString(LOGINMGR_AUTH, "");
    }


    /**
     * 获取cookie + vercode
     */
    public String getCookieVerCode() {
        String cookie = getCookie();
        if (!TextUtils.isEmpty(cookie)) {
            return cookie + ";" + "v=" + ModuleMgr.getAppMgr().getVerCode();
        } else {
            clearCookie();
            return "v=" + ModuleMgr.getAppMgr().getVerCode();
        }
    }


    // ========================  旧逻辑  后续删除======================================================
    // ************************************ 登录用户信息列表存储 *****************************

    private List<UP> userList;  // 维护登录过的用户数据列表，防止多次进行SP读写操作

    /**
     * 获取用户列表
     */
    public List<UP> getUserList() {
        if (userList == null) {
            userList = getUserJson();
        }
        return userList;
    }

    /**
     * @return 获取已登录过的所有用户ID和密码
     */
    private List<UP> getUserJson() {
        List<UP> upList = new ArrayList<>();
        try {
            String key = PSP.getInstance().getString(FinalKey.LOGIN_USER_KEY, null);
            if (!TextUtils.isEmpty(key)) {
                JSONObject jsonObject = new JSONObject(key);
                JSONArray jsonArray = jsonObject.optJSONArray("user");
                UP up;
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.optJSONObject(i);
                    up = new UP();
                    up.setUid(Long.valueOf(EncryptUtil.decryptDES(object.optString("sUid"), FinalKey.UP_DES_KEY)));
                    up.setPw(EncryptUtil.decryptDES(object.optString("sPw"), FinalKey.UP_DES_KEY));
                    up.setTm(object.optLong("tm"));
                    upList.add(up);
                }
            }
        } catch (Exception e) {
            PLogger.printThrowable(e);
        }
        return upList;
    }

    /**
     * 登录后存储账号密码到list配置
     */
    public void putUserInfo(long uid, String pwd) {
        List<UP> sourceList = getUserJson();
        List<UP> reSortList = new ArrayList<>();
        boolean uidRepeat = false;
        UP up;

        // 将以存储的用户数据复制到另一个list中，并保证当前登录用户处于列表首位
        for (int i = 0; i < sourceList.size(); i++) {
            up = sourceList.get(i);
            if (up != null && up.getUid() != 0) {
                if (up.getUid() == uid) {//如果已登录过该uid，更新并添加到列表首位
                    up.setPw(pwd);
                    up.setTm(TimeUtil.getTimeInMillis());
                    reSortList.add(0, up);
                    uidRepeat = true;
                } else {
                    reSortList.add(up);
                }
            }
        }
        if (!uidRepeat) {//用户为首次登录
            reSortList.add(0, new UP(uid, pwd, TimeUtil.getTimeInMillis()));
        }
        putUserJson(reSortList);
    }

    /**
     * 登录后存储账号密码list到本地Json
     *
     * @return true：存储成功
     */
    public boolean putUserJson(List<UP> upList) {
        userList = null;  // 更新本地userList
        try {
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            JSONObject tmpJson;
            for (UP tmp : upList) {
                tmpJson = new JSONObject();
                tmpJson.put("sUid", EncryptUtil.encryptDES(String.valueOf(tmp.getUid()), FinalKey.UP_DES_KEY));
                tmpJson.put("sPw", EncryptUtil.encryptDES(String.valueOf(tmp.getPw()), FinalKey.UP_DES_KEY));
                tmpJson.put("tm", tmp.getTm());
                jsonArray.put(tmpJson);
            }
            jsonObject.put("user", jsonArray);
            PSP.getInstance().put(FinalKey.LOGIN_USER_KEY, jsonObject.toString());
            return true;
        } catch (Exception e) {
            PLogger.printThrowable(e);
            return false;
        }
    }

    /**
     * 移除登录用户
     *
     * @return 被移除的用户
     */
    public UP removeLoginUser(int position) {
        UP user = getUserList().remove(position);
        if (getUserList().size() >= 0) {
            putUserJson(getUserList());
        }
        return user;
    }

    /**
     * 设置登录信息，并发送登录信息。
     *
     * @param uid
     * @param isUserLogin 　进行登录请求或处于登录状态
     * @return
     */
    private boolean setLoginInfo(long uid, boolean isUserLogin) {
        App.cookie = getCookie();
        changeIsLogin(isUserLogin && (TextUtils.isEmpty(App.cookie) || uid == 0) ? 0 : uid);
        MsgMgr.getInstance().sendMsg(MsgType.MT_App_Login, App.isLogin);
        return App.isLogin;
    }

    private void changeIsLogin(long uid) {
        App.uid = uid;
        App.isLogin = uid != 0;
    }

    /**
     * 退出登录，并清空用户登录信息
     */
    public void logout() {
        NotificationsUtils.cancelAll();//如果还有通知栏提示，在退出帐号的时候全部清掉
        setUid("");//清空uid
        clearCookie();//在setLoginInfo方法之前执行
        setLoginInfo(0, true);
    }

    /**
     * 保存单独的 uid
     *
     * @param uid
     */
    public void setUid(String uid) {
        PSP.getInstance().put(LOGINMGR_UID, uid);
    }

    public long getUid() {
        String uid = PSP.getInstance().getString(LOGINMGR_UID, "");
        if (!TextUtils.isEmpty(uid)) {
            return BaseUtil.getLong(uid, 0);
        }
        return 0L;
    }

    /**
     * 初始化登陆信息
     */
    public void initCookie() {
        long uid = getUid();
        if (uid == 0) {
            clearCookie();
            return;
        }
        setLoginInfo(uid, true);
    }

    // ---------------------------登录注册相关接口---------------------------------

    /**
     * 重置密码获取验证码
     *
     * @param phone
     * @param complete
     */
    public void reqForgotsms(String phone, RequestComplete complete) {
//        HashMap<String, Object> post_param = new HashMap<>();
//        post_param.put("phone", phone);
//        post_param.put("sign", App.context.getString(R.string.app_name));
//        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqForgotsms, post_param, complete);
    }

    /**
     * 重置密码
     *
     * @param phone    手机号
     * @param code     验证码
     * @param pwd      密码
     * @param complete
     */
    public void forgotPassword(String phone, String code, String pwd, RequestComplete complete) {
//        HashMap<String, Object> post_param = new HashMap<>();
//        post_param.put("phone", phone);
//        post_param.put("sign", App.context.getString(R.string.app_name));
//        post_param.put("code", code);
//        post_param.put("password", pwd);
//        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.forgotPassword, post_param, complete);
    }
}
